<template>
  <div ref="editorRef"></div>
</template>
<script>
import { onMounted, onBeforeUnmount, ref, watch, nextTick } from 'vue'
import Vditor from 'vditor'
import 'vditor/dist/index.css'
export default {
  name: 'vditorEdit',
  props: {
    content: {
      type: String,
      default: 'Vditor Init OK'
    }
  },
  setup(props) {
    const editorRef = ref()
    let instance
    // 初始化 方法
    function init() {
      instance = new Vditor(editorRef.value, {
        height: 720,
        mode: 'sv',
        toolbarConfig: {
          pin: true
        },
        cache: {
          enable: false
        },
        after: () => {
          instance.setValue(props.content)
        },
        // 这里写上传
        upload: {}
      })
    }
    // 监听传进来的值,set到编辑器里
    watch(
      () => props.content,
      (content) => {
        if (instance) {
          instance.setValue(content)
        }
      },
      {
        immediate: true
      }
    )
    // 初始化编辑器
    onMounted(() => {
      nextTick(() => {
        init()
      })
    })
    // 销毁
    onBeforeUnmount(() => {
      instance.destroy()
      instance = null
    })
    // 获取编辑器内容
    function getEditValue() {
      return instance.getValue()
    }

    return {
      editorRef,
      getEditValue
    }
  }
}
</script>
